package cn.yiya.shiji.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.yiya.shiji.R;
import cn.yiya.shiji.adapter.FilterPopularWordsAdapter;
import cn.yiya.shiji.adapter.GoodsListOrderAdapter;
import cn.yiya.shiji.adapter.MallGoodsAdapter;
import cn.yiya.shiji.adapter.RecordAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MapRequest;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.config.BaseApplication;
import cn.yiya.shiji.config.Configration;
import cn.yiya.shiji.entity.CarCountInfo;
import cn.yiya.shiji.entity.GoodsIdInfo;
import cn.yiya.shiji.entity.MallGoodsDetailObject;
import cn.yiya.shiji.entity.MallLimitOptionInfo;
import cn.yiya.shiji.entity.MallLimitOptionObject;
import cn.yiya.shiji.entity.ParaObject;
import cn.yiya.shiji.entity.PopularDataObject;
import cn.yiya.shiji.entity.SearchHotWords;
import cn.yiya.shiji.entity.SearchRecordObject;
import cn.yiya.shiji.entity.SortInfo;
import cn.yiya.shiji.entity.goodes.NewGoodsItem;
import cn.yiya.shiji.utils.DebugUtil;
import cn.yiya.shiji.utils.NetUtil;
import cn.yiya.shiji.utils.SimpleUtils;
import cn.yiya.shiji.utils.Util;
import cn.yiya.shiji.views.AllListView;

/**
 * 商品列表界面
 * Created by Tom on 2016/5/23.
 */
public class GoodsListActivity extends BaseAppCompatActivity implements View.OnClickListener {
    /*
    顶部搜索条及搜索PopupWindow布局
     */
    private RelativeLayout rlytAutoCtv;
    private AutoCompleteTextView mAutoCompleteTextView;
    private ImageView ivSearchCancle;

    private PopupWindow searchPopupWindow;
    private LinearLayout llytSearchPopupWindow;
    private ScrollView mScrollView;
    private TagFlowLayout tflythotSearch;
    private TagAdapter tagAdapter;
    private LinearLayout llytWords;
    private AllListView alvSearchRecord;
    private RecordAdapter mRecordAdapter;
    private TextView tvNullRecord;
    private Button tvCleanRecord;
    /*
    顶部标题栏
     */
    private ImageView ivTitleBack;
    private TextView tvTitle;
    private TextView tvShopCart;
    private RelativeLayout rlytCar;
    /*
    筛选和排序按钮
     */
    private TextView tvOrder;
    private TextView tvFilter;
    /*
    左侧排序popupwindow
     */
    private PopupWindow orderPopupWindow;
    private LinearLayout llytOrder;
    private RecyclerView rycvOrder;
    private GoodsListOrderAdapter goodsListOrderAdapter;
    /*
    商品列表
     */
    private SwipeRefreshLayout srlytGoodsList;
    private RecyclerView rycvGoodsList;
    private MallGoodsAdapter mallGoodsAdapter;
    private ArrayList<NewGoodsItem> mallGoodsLists = new ArrayList<>();
    /*
    筛选后无商品的提示布局
     */
    private RelativeLayout rlytNollGoods;
    /*
    商品筛选条件
     */
    private MallLimitOptionInfo mInfos = new MallLimitOptionInfo();

    private LayoutInflater mLayoutInflater;
    private Handler mHandle;
    private SharedPreferences sharedPreferences;
    private int shopId;
    private boolean bShow;                                  // 是否显示打折
    private int nOffset = 0;
    private boolean isBottom;
    private int lastVisibleItemPosition;

    public int nFromIn = 0;                                 // 1001-->首页进入 1002-->二级分类进入 1003-->热门商城进入
    private String brand_ids = "";
    private String category_ids = "";
    private String sort_ids = "";
    private String price_ranges_id = "";
    private String genders = "";
    private String color = "";
    private String size = "";
    private String category_name = "";
    private String site_name = "";
    private ParaObject post = new ParaObject();

    private int source;                                     // 为1时是从搜索跳转过来的,此时显示顶部搜索条;为2时从三级分类进入
    private SearchRecordObject object = new SearchRecordObject();
    private List<String> listrecord = new ArrayList<>();
    private String[] data;
    private String word;
    private SearchHotWords hotWords;
    private String[] words;
    private String stamp;
    private SearchHotWords hotData;

    private HashMap<String, String[]>[] datas;
    private PopularDataObject popularDataObject;
    private FilterPopularWordsAdapter filterPopularWordsAdapter;
    private ArrayList<String> arrayList = new ArrayList<>();

    private Runnable myRunnable;

    private static final int REQUEST_FILTER = 111;
    private static final String ALL = "全部";
    private static final int REQUEST_LOGIN = 222;
    private boolean isLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list);
        mLayoutInflater = LayoutInflater.from(this);
        mHandle = new Handler(getMainLooper());
        sharedPreferences = getSharedPreferences(Configration.SHAREDPREFERENCE, MODE_PRIVATE);
        initIntent();
        initViews();
        initEvents();
        init();
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            shopId = intent.getIntExtra("id", 0);
            post.setId(shopId);
            source = intent.getIntExtra("source", 0);
            site_name = intent.getStringExtra("site_name");
            if (source == 2) {
                category_ids = intent.getStringExtra("categoryid");
                category_name = intent.getStringExtra("categoryname");
            }
            nFromIn = intent.getIntExtra("type", 0);
            bShow = intent.getBooleanExtra("show", false);
            word = intent.getStringExtra("word");
//            if (word != null) {
//                word = URLEncoder.encode(word);
//            }
        }
    }

    //初始化筛选选项，手动添加全部和默认标签
    private void initDefaultData() {
        ArrayList<SortInfo> genderList = new ArrayList<>();
        ArrayList<SortInfo> brandList = new ArrayList<>();
        ArrayList<SortInfo> categoryList = new ArrayList<>();
        ArrayList<SortInfo> priceList = new ArrayList<>();
//        ArrayList<SortInfo> sizeList = new ArrayList<>();
        ArrayList<SortInfo> colorList = new ArrayList<>();
        ArrayList<SortInfo> sortList = new ArrayList<>();

        SortInfo gInfo = new SortInfo();
        gInfo.setCheck(true);
        gInfo.setName(ALL);
        gInfo.setKey("");
        genderList.add(gInfo);
        mInfos.setGenders(genderList);

//        SortInfo bInfo = new SortInfo();
//        bInfo.setName(ALL);
//        bInfo.setCheck(true);
//        brandList.add(bInfo);
//        mInfos.setBrands(brandList);

        SortInfo cInfo = new SortInfo();
        cInfo.setCheck(true);
        cInfo.setName(ALL);
        categoryList.add(cInfo);
        mInfos.setCategories(categoryList);

        SortInfo pInfo = new SortInfo();
        pInfo.setCheck(true);
        pInfo.setName(ALL);
        priceList.add(pInfo);
        mInfos.setPrice_ranges(priceList);

//        SortInfo sInfo = new SortInfo();
//        sInfo.setCheck(true);
//        sInfo.setName(ALL);
//        sizeList.add(sInfo);
//        mInfos.setSize(sizeList);

        SortInfo soInfo = new SortInfo();
        soInfo.setCheck(true);
        soInfo.setName("默认排序");
        sortList.add(soInfo);
        mInfos.setSorts(sortList);

        SortInfo coInfo = new SortInfo();
        coInfo.setCheck(true);
        coInfo.setName(ALL);
        colorList.add(coInfo);
        mInfos.setColor(colorList);
    }

    // 获取筛选条件
    private void getLimitData() {
        if (myRunnable != null) {
            mHandle.removeCallbacks(myRunnable);
        }
        myRunnable = new MyRunnable();
        mHandle.post(myRunnable);
    }

    @Override
    protected void initViews() {
        rlytAutoCtv = (RelativeLayout) findViewById(R.id.rlyt_search);
        mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.title_search);
        mAutoCompleteTextView.setDropDownWidth(SimpleUtils.getScreenWidth(this));
        ivSearchCancle = (ImageView) findViewById(R.id.imageview);

        popularDataObject = new Gson().fromJson(sharedPreferences.getString("popularData", ""), PopularDataObject.class);
        if (popularDataObject != null) {
            arrayList = popularDataObject.arrayList;
            stamp = popularDataObject.stamp;
            datas = popularDataObject.datas;
        }
        if (arrayList != null) {
            filterPopularWordsAdapter = new FilterPopularWordsAdapter(datas, GoodsListActivity.this, 2, arrayList);
            mAutoCompleteTextView.setAdapter(filterPopularWordsAdapter);
            filterPopularWordsAdapter.setOnItemClickListener(new FilterPopularWordsAdapter.OnItemClickListener() {
                @Override
                public void onClickListener(String record) {
                    addRecord(record);
                }
            });
        }
        if (word != null) {
            mAutoCompleteTextView.setText(URLDecoder.decode(word));
        }

        ivTitleBack = (ImageView) findViewById(R.id.title_back);
        tvTitle = (TextView) findViewById(R.id.title_txt);
        tvTitle.setText("商品列表");
        if (!TextUtils.isEmpty(site_name)) {
            tvTitle.setText(site_name);
        }
        if (!TextUtils.isEmpty(category_name)) {
            tvTitle.setText(category_name);
        }
        tvShopCart = (TextView) findViewById(R.id.toolbar_right_count);
        rlytCar = (RelativeLayout) findViewById(R.id.toolbar_right_layout);

        tvOrder = (TextView) findViewById(R.id.tv_order);
        tvFilter = (TextView) findViewById(R.id.tv_filter);

        srlytGoodsList = (SwipeRefreshLayout) findViewById(R.id.srlyt_goods_list);
        rycvGoodsList = (RecyclerView) findViewById(R.id.recycler_mall_list);
        rycvGoodsList.setItemAnimator(new DefaultItemAnimator());
        rycvGoodsList.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        rlytNollGoods = (RelativeLayout) findViewById(R.id.rl_reminder);

        rlytDefaultNullView = (RelativeLayout) findViewById(R.id.rlyt_default_null_view);
        tvDefaultNull = (TextView) findViewById(R.id.tv_default_null);
        llytDefaultOffNet = (LinearLayout) findViewById(R.id.llyt_off_net);
        tvReload = (TextView) findViewById(R.id.tv_reload);
        initDefaultNullView(R.mipmap.zanwusousuojieguo, "暂无结果", this);
    }

    @Override
    protected void initEvents() {
        mAutoCompleteTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                llytWords.setVisibility(View.VISIBLE);
                mScrollView.setVisibility(View.GONE);
                if (TextUtils.isEmpty(s.toString())) {
                    ivSearchCancle.setVisibility(View.GONE);
                    llytWords.setVisibility(View.GONE);
                    mScrollView.setVisibility(View.VISIBLE);
                } else {
                    ivSearchCancle.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mAutoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {                                                     // 获得焦点动作
                    if (mAutoCompleteTextView.getText().toString() != null) {
                        ivSearchCancle.setVisibility(View.VISIBLE);
                    }
                    showSearchView();
                    mScrollView.setVisibility(View.VISIBLE);

                    object = new Gson().fromJson(sharedPreferences.getString("record", ""), SearchRecordObject.class);
                    if (object != null) {
                        listrecord = object.getList();
                        Collections.reverse(listrecord);
                        if (listrecord.size() > 5) {
                            listrecord = listrecord.subList(0, 5);
                        }
                        mRecordAdapter = new RecordAdapter(listrecord, GoodsListActivity.this, 1);
                        mRecordAdapter.setOnItemClickListener(new RecordAdapter.OnItemClickListener() {
                            @Override
                            public void onClickListener(String record) {
                                addRecord(record);
                            }
                        });
                        alvSearchRecord.setAdapter(mRecordAdapter);                                     // 搜索记录
                        tvNullRecord.setVisibility(View.GONE);                                          // 取消无记录提示
                        tvCleanRecord.setVisibility(View.VISIBLE);                                      // 清除记录提示
                    } else {
                        tvNullRecord.setVisibility(View.VISIBLE);                                       // 显示无记录提示
                        tvCleanRecord.setVisibility(View.GONE);                                         // 取消清除记录提示
                    }
                    if (mAutoCompleteTextView.getText().toString() != "") {
                        llytWords.setVisibility(View.VISIBLE);
                        mScrollView.setVisibility(View.GONE);                                           // 搜索历史页面隐藏
                        mAutoCompleteTextView.setSelection(mAutoCompleteTextView.getText().length());
                        filterData(mAutoCompleteTextView.getText().toString());
                    }
                }
            }
        });
        mAutoCompleteTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {                                       // 点击回车键发送信息
                    ArrayList<String> mList = new ArrayList<>();
                    if ((new Gson().fromJson(sharedPreferences.getString("record", ""), SearchRecordObject.class)) != null) {
                        mList = (new Gson().fromJson(sharedPreferences.getString("record", ""), SearchRecordObject.class)).getList();
                        for (int i = 0; i < mList.size(); i++) {
                            if (mAutoCompleteTextView.getText().toString().equals(mList.get(i).toString())) {
                                mList.remove(i);
                            }
                        }
                        if (!mAutoCompleteTextView.getText().toString().equals("")) {
                            mList.add(mAutoCompleteTextView.getText().toString());
                            object = new SearchRecordObject();
                            object.setList(mList);
                            String json = new Gson().toJson(object);
                            Util.saveLocalSearchRecord(mHandle, sharedPreferences, json);
                        }
                    } else {
                        if (!mAutoCompleteTextView.getText().toString().equals("")) {
                            mList.add(mAutoCompleteTextView.getText().toString());
                            object = new SearchRecordObject();
                            object.setList(mList);
                            String json = new Gson().toJson(object);
                            Util.saveLocalSearchRecord(mHandle, sharedPreferences, json);
                        }
                    }
                    if (!mAutoCompleteTextView.getText().toString().equals("")) {
                        addRecord(mAutoCompleteTextView.getText().toString());
                    } else {
                        Util.toast(GoodsListActivity.this, "搜索不能为空", true);
                    }
                    return true;
                }
                return false;
            }
        });

        ivTitleBack.setOnClickListener(this);
        rlytCar.setOnClickListener(this);

        tvOrder.setOnClickListener(this);
        tvFilter.setOnClickListener(this);

        srlytGoodsList.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDataBySource();
            }
        });

        rycvGoodsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                // 通过适配器的个数和最后可见的数据来判断是否需要加载数据，这里减3表示后台预加载
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                if ((visibleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE &&
                        (lastVisibleItemPosition) >= totalItemCount - 20) && !isBottom) {
                    loadMore();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                StaggeredGridLayoutManager staggeredGridLayoutManager
                        = (StaggeredGridLayoutManager) layoutManager;
                int[] lastPositions = new int[2];
                if (lastPositions == null) {
                    lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
                }
                staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
                lastVisibleItemPosition = Math.max(lastPositions[0], lastPositions[1]);
            }
        });
    }

    @Override
    protected void init() {
        initDefaultData();
        if (source == 1) {
            rlytAutoCtv.setVisibility(View.VISIBLE);
            tvTitle.setVisibility(View.GONE);
            post.setWord(word);
            getSearchGoodsList(word);
            getSearchLimitList(word);           // 获取排序筛选条件
        } else {
            getMallData(true);
            getLimitData();                     // 获取排序筛选条件
        }
//        initCarCount();
    }

    public class MyRunnable implements Runnable {
        @Override
        public void run() {
            HashMap<String, String> maps = new HashMap<>();
            maps.put("id", String.valueOf(shopId));
            maps.put("brand", String.valueOf(0));
            if (source == 2) {
                maps.put("category_ids", category_ids);
            }
            switch (nFromIn) {
                case Configration.MALL_HOME:
                    new RetrofitRequest<MallLimitOptionObject>(ApiRequest.getApiShiji().getMallHomeOption(maps)).handRequest(
                            new MsgCallBack() {
                                @Override
                                public void onResult(HttpMessage msg) {
                                    handleMessage(msg);
                                }
                            }
                    );
                    break;
                case Configration.SECONDE_TYPE:
                    new RetrofitRequest<MallLimitOptionObject>(ApiRequest.getApiShiji().getCategoryOption(maps)).handRequest(
                            new MsgCallBack() {
                                @Override
                                public void onResult(HttpMessage msg) {
                                    handleMessage(msg);
                                }
                            }
                    );
                    break;
                case Configration.HOT_GOODS:
                    new RetrofitRequest<MallLimitOptionObject>(ApiRequest.getApiShiji().getHotMallOption(maps)).handRequest(
                            new MsgCallBack() {
                                @Override
                                public void onResult(HttpMessage msg) {
                                    handleMessage(msg);
                                }
                            }
                    );
                    break;
            }
        }
    }

    private void handleMessage(HttpMessage msg) {
        if (msg.isSuccess()) {
            MallLimitOptionObject object = (MallLimitOptionObject) msg.obj;

            //对品类数组进行分类
            if (object == null || object.getList() == null) {
                return;
            }
            ArrayList<SortInfo> caList = object.getList().getCategories();

            HashMap<String, ArrayList<SortInfo>> maps = new HashMap<>();

            for (int i = 0; i < caList.size(); i++) {
                String productTypeId = caList.get(i).getProduct_type_id() + "";
                if (maps.get(productTypeId) == null) {
                    ArrayList<SortInfo> productTypeIds = new ArrayList<>();
                    productTypeIds.add(caList.get(i));
                    maps.put(productTypeId, productTypeIds);
                } else {
                    ArrayList<SortInfo> productTypeIds = maps.get(productTypeId);
                    productTypeIds.add(caList.get(i));
                    maps.put(productTypeId, productTypeIds);
                }
            }

            Iterator iter = maps.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                ArrayList<SortInfo> productCategories = (ArrayList<SortInfo>) entry.getValue();
                //当从三级分类进入时将全部的categoryid设为所选类别的categoryid
                if(source==2 && !TextUtils.isEmpty(category_ids)){
                    mInfos.getCategories().clear();
                    ArrayList<SortInfo> categoryList=new ArrayList<SortInfo>();
                    SortInfo cInfo=productCategories.get(0).clone();
                    cInfo.setCheck(true);
                    cInfo.setName(ALL);
                    categoryList.add(cInfo);
                    mInfos.setCategories(categoryList);
                }
                mInfos.getCategories().addAll(productCategories);
            }


            mInfos.getGenders().addAll(object.getList().getGenders());
            if (object.getList().getSize() != null) {
                for (int i = 0; i < object.getList().getSize().size(); i++) {
                    SortInfo sortInfo = new SortInfo();
                    sortInfo.setName(ALL);
                    sortInfo.setCheck(true);
                    object.getList().getSize().get(i).getSizes().add(0, sortInfo);
                }
            }
            mInfos.setSize(object.getList().getSize());
            mInfos.getPrice_ranges().addAll(object.getList().getPrice_ranges());
            mInfos.getColor().addAll(object.getList().getColor());
            mInfos.getSorts().addAll(object.getList().getSorts());
        }
    }

    // 获取搜索之后的商品列表
    private void getSearchGoodsList(String str) {
        showPreDialog("正在加载");
        nOffset = 0;
        post.setCategory_ids(category_ids);
        post.setGenders(genders);
        post.setBrand_ids(brand_ids);
        post.setCount(0);
        post.setSort_id(sort_ids);
        post.setPrice_ranges_id(price_ranges_id);
        post.setSize(size);
        post.setColor(color);
        new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getSearchGoodes(MapRequest.setMallListMap(
                nOffset, post))).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    MallGoodsDetailObject object = (MallGoodsDetailObject) msg.obj;
                    hidePreDialog();
                    if (object != null && object.getList().size() > 0) {
                        if (mallGoodsLists != null) {
                            mallGoodsLists.clear();
                        }
                        isBottom = false;
                        mallGoodsLists.addAll(object.getList());

                        BaseApplication.testList = mallGoodsLists;

                        if (mallGoodsAdapter == null) {
                            mallGoodsAdapter = new MallGoodsAdapter(GoodsListActivity.this, mallGoodsLists, bShow);
                            rycvGoodsList.setAdapter(mallGoodsAdapter);
                            rlytNollGoods.setVisibility(View.GONE);

                            hidePreDialog();
                            mallGoodsAdapter.setOnItemClickListener(new MallGoodsAdapter.OnItemClickListener() {
                                @Override
                                public void OnItemClick(final NewGoodsItem info) {
                                    gotoGoodsDetail(info);
                                }
                            });
                        } else {
                            rlytNollGoods.setVisibility(View.GONE);
                            mallGoodsAdapter.setmLists(mallGoodsLists);
                            rycvGoodsList.getAdapter().notifyDataSetChanged();
                            rycvGoodsList.scrollToPosition(0);
                        }
                        setSuccessView(srlytGoodsList);
                    } else {
                        setNullView(srlytGoodsList);
                        if (mallGoodsLists != null) {
                            mallGoodsLists.clear();
                        }
                        if (mallGoodsAdapter != null) {
                            rycvGoodsList.getAdapter().notifyDataSetChanged();
                        }
                    }
                    srlytGoodsList.setRefreshing(false);
                } else {
                    hidePreDialog();
                    srlytGoodsList.setRefreshing(false);
                    if (!NetUtil.IsInNetwork(GoodsListActivity.this)) {
                        setOffNetView(srlytGoodsList);
                    }
                }
            }
        });
        mAutoCompleteTextView.clearFocus();
    }

    // 获取搜索之后的商品的过滤选项
    private void getSearchLimitList(String word) {
        HashMap<String, String> maps = new HashMap<>();
        maps.put("word", word);
        maps.put("brand", String.valueOf(0));
        new RetrofitRequest<MallLimitOptionObject>(ApiRequest.getApiShiji().getSearchLimitList(maps)).handRequest(
                new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        if (msg.isSuccess()) {
                            MallLimitOptionObject object = (MallLimitOptionObject) msg.obj;
                            if (object != null) {
                                if (object.getList().getGenders() != null) {
                                    initDefaultFirstData(mInfos.getGenders(), 0);
                                    mInfos.getGenders().addAll(object.getList().getGenders());
                                }
                                if (object.getList().getCategories() != null) {
                                    initDefaultFirstData(mInfos.getCategories(), 1);
                                    mInfos.getCategories().addAll(object.getList().getCategories());
                                }
                                if (object.getList().getSorts() != null) {
                                    initDefaultFirstData(mInfos.getSorts(), 2);
                                    mInfos.getSorts().addAll(object.getList().getSorts());
                                }
                                if (object.getList().getPrice_ranges() != null) {
                                    initDefaultFirstData(mInfos.getPrice_ranges(), 3);
                                    mInfos.getPrice_ranges().addAll(object.getList().getPrice_ranges());
                                }
                                if (object.getList().getColor() != null) {
                                    initDefaultFirstData(mInfos.getColor(), 4);
                                    mInfos.getColor().addAll(object.getList().getColor());
                                }
                                if (object.getList().getSize() != null) {
                                    for (int i = 0; i < object.getList().getSize().size(); i++) {
                                        SortInfo sortInfo = new SortInfo();
                                        sortInfo.setName(ALL);
                                        sortInfo.setCheck(true);
                                        object.getList().getSize().get(i).getSizes().add(0, sortInfo);
                                    }
                                    mInfos.setSize(object.getList().getSize());
                                }

                            }
                        }

                    }
                }
        );
    }

    private void getDataBySource() {
        if (source == 1) {
            getSearchGoodsList("");
        } else {
            getMallData(true);
        }
    }

    // 获取商品数据
    private void getMallData(boolean bShowDialog) {
        if (bShowDialog) {
            showPreDialog("正在加载");
        }
        nOffset = 0;
        post.setCategory_ids(category_ids);
        post.setGenders(genders);
        post.setBrand_ids(brand_ids);
        post.setCount(0);
        post.setSort_id(sort_ids);
        post.setPrice_ranges_id(price_ranges_id);
        post.setSize(size);
        post.setColor(color);
        switch (nFromIn) {
            case Configration.MALL_HOME:
                new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getMallHomeList(MapRequest.setMallListMap(
                        nOffset, post))).handRequest(new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        handleListMessage(msg);
                    }
                });
                break;
            case Configration.SECONDE_TYPE:
                new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getCategoryList(MapRequest.setMallListMap(
                        nOffset, post))).handRequest(new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        handleListMessage(msg);
                    }
                });
                break;
            case Configration.HOT_GOODS:
                new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getHotMallList(MapRequest.setMallListMap(
                        nOffset, post))).handRequest(new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        handleListMessage(msg);
                    }
                });
                break;
        }
    }

    private void handleListMessage(HttpMessage msg) {
        hidePreDialog();
        if (msg.isSuccess()) {
            MallGoodsDetailObject object = (MallGoodsDetailObject) msg.obj;
            if (object != null && object.getList().size() > 0) {
                if (mallGoodsLists != null) {
                    mallGoodsLists.clear();
                }
                isBottom = false;
                mallGoodsLists.addAll(object.getList());

                BaseApplication.testList = mallGoodsLists;

                if (mallGoodsAdapter == null) {
                    mallGoodsAdapter = new MallGoodsAdapter(GoodsListActivity.this, mallGoodsLists, bShow);
                    rycvGoodsList.setAdapter(mallGoodsAdapter);

                    mallGoodsAdapter.setOnItemClickListener(new MallGoodsAdapter.OnItemClickListener() {
                        @Override
                        public void OnItemClick(final NewGoodsItem info) {
                            gotoGoodsDetail(info);
                        }
                    });
                } else {
                    rycvGoodsList.getAdapter().notifyDataSetChanged();
                    rycvGoodsList.scrollToPosition(0);
                }
                setSuccessView(srlytGoodsList);
            } else {
                setNullView(srlytGoodsList);
                if (mallGoodsLists != null) {
                    mallGoodsLists.clear();
                }
                if (mallGoodsAdapter != null) {
                    rycvGoodsList.getAdapter().notifyDataSetChanged();
                }
            }
            srlytGoodsList.setRefreshing(false);
        } else {
            hidePreDialog();
            srlytGoodsList.setRefreshing(false);
            if (!NetUtil.IsInNetwork(GoodsListActivity.this)) {
                setOffNetView(srlytGoodsList);
            }
        }
    }

    private void showSearchView() {

        llytSearchPopupWindow = (LinearLayout) mLayoutInflater.inflate(R.layout.activity_new_search, null);
        searchPopupWindow = new PopupWindow(llytSearchPopupWindow, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        searchPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        searchPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        llytSearchPopupWindow.findViewById(R.id.rlyt_search).setVisibility(View.GONE);
        mScrollView = (ScrollView) llytSearchPopupWindow.findViewById(R.id.sv_scroll);
        tflythotSearch = (TagFlowLayout) llytSearchPopupWindow.findViewById(R.id.tfl_search_tips);
        llytWords = (LinearLayout) llytSearchPopupWindow.findViewById(R.id.ll_words);
        alvSearchRecord = (AllListView) llytSearchPopupWindow.findViewById(R.id.lv_record);
        tvNullRecord = (TextView) llytSearchPopupWindow.findViewById(R.id.tv_record);
        tvCleanRecord = (Button) llytSearchPopupWindow.findViewById(R.id.btn_clean_record);

        mAutoCompleteTextView.requestFocus();
        mAutoCompleteTextView.setFocusable(true);
        searchPopupWindow.setFocusable(false);
        searchPopupWindow.setOutsideTouchable(false);
        searchPopupWindow.showAsDropDown(mAutoCompleteTextView);
        popularDataObject = new Gson().fromJson(sharedPreferences.getString("popularData", ""), PopularDataObject.class);
        if (popularDataObject != null) {
            arrayList = popularDataObject.arrayList;
            stamp = popularDataObject.stamp;
        }
        getSearchHotWords();
        initSearchEvent();
    }

    //  从本地模糊查找
    private void filterData(String filterStr) {
        ArrayList<String> wordsList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr)) {
            llytWords.setVisibility(View.GONE);
            mScrollView.setVisibility(View.VISIBLE);                     // 搜索历史页面显示
        } else {
            wordsList.clear();
            if (data != null) {
                for (int i = 0; i < data.length; i++) {
                    String word = data[i];
                    if (word.toUpperCase().startsWith(filterStr.toString().toUpperCase())) {
                        wordsList.add(word);
                    } else {
                    }
                }
            }
            RecordAdapter recordAdapter = new RecordAdapter(wordsList, GoodsListActivity.this, 2);
            recordAdapter.setOnItemClickListener(new RecordAdapter.OnItemClickListener() {
                @Override
                public void onClickListener(String record) {
                    addRecord(record);
                }
            });
            Util.showIMETool(GoodsListActivity.this, llytSearchPopupWindow);
        }
    }

    // 获取热门搜索列表
    private void getSearchHotWords() {
        new RetrofitRequest<SearchHotWords>(ApiRequest.getApiShiji().getHotSearch()).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    hotWords = (SearchHotWords) msg.obj;
                    words = hotWords.getWords();
                }
                tagAdapter = new TagAdapter(words) {                                                // 热门搜索数据
                    @Override
                    public View getView(FlowLayout parent, int position, Object o) {
                        TextView tvPrices = (TextView) mLayoutInflater.inflate(R.layout.search_words_item, tflythotSearch, false);
                        tvPrices.setText(words[position]);
                        return tvPrices;
                    }
                };
                tflythotSearch.setAdapter(tagAdapter);
            }
        });
    }

    // 获取最新的搜索数据
//    public void getShopSearchData() {
//        HttpRequest.getInstance().getShopSearchData(mHandle, stamp, new MsgCallBack() {
//            @Override
//            public void onResult(HttpMessage msg) {
//                if (msg.isSuccess()) {
//                    hotData = (SearchHotWords) msg.obj;
//                    if (hotData.getData() != null) {
//                        String json = new Gson().toJson(hotData);
//                        Util.saveServerSearchData(mHandle, sharedPreferences, json);
//                    }
//                }
//            }
//        });
//    }

    private void initSearchEvent() {
        tflythotSearch.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                addRecord(words[position]);
                Util.hintIMETool(GoodsListActivity.this, view);
                return false;
            }
        });
        alvSearchRecord.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                addRecord(listrecord.get(position));
                Util.hintIMETool(GoodsListActivity.this, view);
            }
        });
//        mAutoCompleteTextView.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                llytWords.setVisibility(View.VISIBLE);
//                mScrollView.setVisibility(View.GONE);
//                if (TextUtils.isEmpty(s.toString())) {
//                    ivSearchCancle.setVisibility(View.GONE);
//                    llytWords.setVisibility(View.GONE);
//                    mScrollView.setVisibility(View.VISIBLE);
//                } else {
//                    ivSearchCancle.setVisibility(View.VISIBLE);
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });
        mScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {                                             // 华东界面时隐藏输入法
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        Util.hintIMETool(GoodsListActivity.this, v);
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        tvCleanRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listrecord.clear();
                mRecordAdapter.notifyDataSetChanged();
                Util.cleanLocalSearchRecord(mHandle, sharedPreferences);
                tvCleanRecord.setVisibility(View.GONE);
                tvNullRecord.setVisibility(View.VISIBLE);
            }
        });
        ivSearchCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAutoCompleteTextView.setText("");
            }
        });
    }

    private void addRecord(String word) {
        if (TextUtils.isEmpty(word)) {
            Util.toast(GoodsListActivity.this, "搜索不能为空", true);
            return;
        }

        ArrayList<String> mList = new ArrayList<>();

        SearchRecordObject searchRecordObject = (new Gson().fromJson(sharedPreferences.getString("record", ""), SearchRecordObject.class));
        if (searchRecordObject != null) {
            mList = searchRecordObject.getList();
            for (int i = 0; i < mList.size(); i++) {
                if (word.equals(mList.get(i).toString())) {
                    mList.remove(i);
                }
            }
        }
        mList.add(word);
        object = new SearchRecordObject();
        object.setList(mList);
        String json = new Gson().toJson(object);
        Util.saveLocalSearchRecord(mHandle, sharedPreferences, json);
        searchPopupWindow.dismiss();
        searchPopupWindow = null;

//        word = URLEncoder.encode(word);
        post.setWord(word);
        brand_ids = "";
        category_ids = "";
        color = "";
        size = "";
        sort_ids = "";
        price_ranges_id = "";
        genders = "";
        getSearchGoodsList(word);
        getSearchLimitList(word);
        llytWords.setVisibility(View.GONE);
        mAutoCompleteTextView.setText(URLDecoder.decode(word));
        mAutoCompleteTextView.clearFocus();
    }

    /**
     * 删除list中除第一个数据
     *
     * @param list
     */
    private void initDefaultFirstData(ArrayList<SortInfo> list, int type) {
        list.clear();
        switch (type) {
            case 0:     // 表示人群
                SortInfo gInfo = new SortInfo();
                gInfo.setCheck(true);
                gInfo.setName(ALL);
                gInfo.setKey("");
                list.add(gInfo);
                break;
            case 1:     // 表示品类
                SortInfo cInfo = new SortInfo();
                cInfo.setCheck(true);
                cInfo.setName(ALL);
                list.add(cInfo);
                break;
            case 2:     // 表示排序
                SortInfo sInfo = new SortInfo();
                sInfo.setCheck(true);
                sInfo.setName("默认排序");
                list.add(sInfo);
                break;
            case 3:     // 表示价格
                SortInfo pInfo = new SortInfo();
                pInfo.setCheck(true);
                pInfo.setName(ALL);
                list.add(pInfo);
                break;
            case 4:     // 表示颜色
                SortInfo coInfo = new SortInfo();
                coInfo.setCheck(true);
                coInfo.setName(ALL);
                list.add(coInfo);
                break;
        }
    }

    // 2016-03-07
    // 获取最新的搜索数据


//    public void getPopularData() {
//        HttpRequest.getInstance().getPopularData(mHandle, stamp, new MsgCallBack() {
//            @Override
//            public void onResult(HttpMessage msg) {
//                if (msg.isSuccess()) {
//                    SearchPopularWords searchPopularWords = (SearchPopularWords) msg.obj;
//                    datas = searchPopularWords.data;
//                    if (datas != null) {
//                        filterBrands(datas);
//                        popularDataObject = new PopularDataObject();
//                        popularDataObject.setArrayList(arrayList);
//                        popularDataObject.setStamp(searchPopularWords.stamp);
//                        popularDataObject.setDatas(datas);
//                        String json = new Gson().toJson(popularDataObject);
//                        Util.savePopularSearchData(mHandle, sharedPreferences, json);
//                    }
//                }
//            }
//        });
//    }


//    public void filterBrands(HashMap<String, String[]>[] data) {
//        for (int i = 0; i < data.length; i++) {
//            Map map = data[i];
//            Iterator iterator = map.entrySet().iterator();
//            while (iterator.hasNext()) {
//                Map.Entry entry = (Map.Entry) iterator.next();
//                String localword = (String) entry.getKey();
//                arrayList.add(localword);
//            }
//        }
//    }

//    public void OpenLeftMenu(View view) {
//        Fragment fragment = new GoodsListOrderFragment();
//        Bundle bundle = new Bundle();
//        if (mInfos != null) {
//            bundle.putString("data", new Gson().toJson(mInfos));
//        }
////        bundle.putInt("type", 0);                                       // 0表示商城列表 1表示品牌详情
//        fragment.setArguments(bundle);
//        FragmentManager fragmentManager = getSupportFragmentManager();
//        fragmentManager.beginTransaction().replace(R.id.flyt_order, fragment).commit();
//        mDrawerLayout.openDrawer(Gravity.LEFT);
//        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED,
//                Gravity.LEFT);
//    }

    // 加载更多
    private void loadMore() {
        nOffset += 40;
        post.setCount(0);
        if (source == 1) {
            new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getSearchGoodes(MapRequest.setMallListMap(
                    nOffset, post))).handRequest(new MsgCallBack() {
                @Override
                public void onResult(HttpMessage msg) {
                    if (msg.isSuccess()) {
                        MallGoodsDetailObject object = (MallGoodsDetailObject) msg.obj;
                        if (object != null && object.getList().size() > 0) {
                            mallGoodsLists.addAll(object.getList());
                            rycvGoodsList.getAdapter().notifyDataSetChanged();
                        } else {
                            isBottom = true;
                        }
                    }
                }
            });
        } else {
            switch (nFromIn) {
                case Configration.MALL_HOME:
                    new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getMallHomeList(MapRequest.setMallListMap(
                            nOffset, post))).handRequest(new MsgCallBack() {
                        @Override
                        public void onResult(HttpMessage msg) {
                            handleMoreMessage(msg);
                        }
                    });
                    break;
                case Configration.SECONDE_TYPE:
                    new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getCategoryList(MapRequest.setMallListMap(
                            nOffset, post))).handRequest(new MsgCallBack() {
                        @Override
                        public void onResult(HttpMessage msg) {
                            handleMoreMessage(msg);
                        }
                    });
                    break;
                case Configration.HOT_GOODS:
                    new RetrofitRequest<MallGoodsDetailObject>(ApiRequest.getApiShiji().getHotMallList(MapRequest.setMallListMap(
                            nOffset, post))).handRequest(new MsgCallBack() {
                        @Override
                        public void onResult(HttpMessage msg) {
                            handleMoreMessage(msg);
                        }
                    });
                    break;
            }
        }
    }

    private void handleMoreMessage(HttpMessage msg) {
        if (msg.isSuccess()) {
            MallGoodsDetailObject object = (MallGoodsDetailObject) msg.obj;
            if (object != null && object.getList().size() > 0) {
                mallGoodsLists.addAll(object.getList());
                rycvGoodsList.getAdapter().notifyDataSetChanged();
            } else {
                isBottom = true;
            }
        }
    }

    // 弹出左侧排序
    private void showOrderPopwindow() {
        tvOrder.setSelected(true);
        llytOrder = (LinearLayout) mLayoutInflater.inflate(R.layout.fragment_goods_list_order, null);
        rycvOrder = (RecyclerView) llytOrder.findViewById(R.id.rycv_goods_list_order);
        rycvOrder.setItemAnimator(new DefaultItemAnimator());
        rycvOrder.setLayoutManager(new LinearLayoutManager(this));
        goodsListOrderAdapter = new GoodsListOrderAdapter(this, mInfos);
        rycvOrder.setAdapter(goodsListOrderAdapter);

        int width = SimpleUtils.getScreenWidth(this) / 2;
        int heigh = SimpleUtils.getScreenHeight(this) - SimpleUtils.dp2px(this, 100);
        orderPopupWindow = new PopupWindow(llytOrder, width, heigh);
        orderPopupWindow.setFocusable(true);
        orderPopupWindow.setOutsideTouchable(true);
        orderPopupWindow.setBackgroundDrawable(new BitmapDrawable(null, ""));
        orderPopupWindow.setAnimationStyle(R.style.order_popwindow_anim_style);

        orderPopupWindow.showAsDropDown(findViewById(R.id.llyt_order_filter), 0, 2);

        goodsListOrderAdapter.setOnItemClickListener(new GoodsListOrderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(MallLimitOptionInfo mInfos) {
                getCommitData(mInfos);
                orderPopupWindow.dismiss();
            }
        });

        orderPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tvOrder.setSelected(false);
            }
        });

    }

    //  确定，提交筛选项
    public void getCommitData(MallLimitOptionInfo data) {
        if (data != null) {
            genders = "";
            sort_ids = "";
            price_ranges_id = "";
            brand_ids = "";
            color = "";

            mInfos = data;

            if (mInfos.getGenders() != null) {
                for (int i = 0; i < mInfos.getGenders().size(); i++) {
                    SortInfo gInfo = mInfos.getGenders().get(i);
                    if (gInfo.isCheck()) {
                        genders = gInfo.getKey();
                    }
                }
            }


            if (mInfos.getCategories() != null) {
                for (int i = 0; i < mInfos.getCategories().size(); i++) {
                    SortInfo cInfo = mInfos.getCategories().get(i);
                    if (cInfo.isCheck()) {
                        category_ids = cInfo.getId() + "";
                        if (mInfos.getSize() != null) {
                            for (int j = 0; j < mInfos.getSize().size(); j++) {
                                if (cInfo.getProduct_type_id() == mInfos.getSize().get(j).getProduct_type_id()) {
                                    ArrayList<SortInfo> sizeList = mInfos.getSize().get(j).getSizes();
                                    for (int n = 0; n < sizeList.size(); n++) {
                                        if (sizeList.get(n).isCheck()) {
                                            size = sizeList.get(n).getId() + "";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }


            if (mInfos.getPrice_ranges() != null) {
                for (int i = 0; i < mInfos.getPrice_ranges().size(); i++) {
                    SortInfo pInfo = mInfos.getPrice_ranges().get(i);
                    if (pInfo.isCheck()) {
                        price_ranges_id = "" + pInfo.getId();
                    }
                }
            }

            if (mInfos.getSorts() != null) {
                for (int i = 0; i < mInfos.getSorts().size(); i++) {
                    SortInfo sInfo = mInfos.getSorts().get(i);
                    if (sInfo.isCheck()) {
                        sort_ids = "" + sInfo.getId();
                    }
                }
            }

            if (mInfos.getColor() != null) {
                for (int i = 0; i < mInfos.getColor().size(); i++) {
                    SortInfo coInfo = mInfos.getColor().get(i);
                    if (coInfo.isCheck()) {
                        color = "" + coInfo.getName();
                    }
                }
            }

            if (mInfos.getBrands() != null) {
                for (int i = 0; i < mInfos.getBrands().size(); i++) {
                    SortInfo bInfo = mInfos.getBrands().get(i);
                    if (bInfo.isCheck()) {
                        if (brand_ids.equals("")) {
                            brand_ids = bInfo.getId() + "";
                        } else {
                            brand_ids += "," + bInfo.getId();
                        }
                    }
                }
            }
//            for (int i = 0; i < mInfos.getGenders().size(); i++) {
//                SortInfo gInfo = mInfos.getGenders().get(i);
//                if (gInfo.isCheck()) {
//                    if (genders.equals("")) {
//                        genders = gInfo.getKey();
//                    } else {
//                        genders += "," + gInfo.getKey();
//                    }
//                }
//            }
//
//            for (int i = 0; i < mInfos.getCategories().size(); i++) {
//                SortInfo cInfo = mInfos.getCategories().get(i);
//                if (cInfo.isCheck()) {
//                    if (category_ids.equals("")) {
//                        category_ids = "" + cInfo.getId();
//                    } else {
//                        category_ids += "," + cInfo.getId();
//                    }
//                }
//            }
//
//            for (int i = 0; i < mInfos.getPrice_ranges().size(); i++) {
//                SortInfo pInfo = mInfos.getPrice_ranges().get(i);
//                if (pInfo.isCheck()) {
//                    if (price_ranges_id.equals("")) {
//                        price_ranges_id = "" + pInfo.getId();
//                    } else {
//                        price_ranges_id += "," + pInfo.getId();
//                    }
//                }
//            }
//
//            for (int i = 0; i < mInfos.getSorts().size(); i++) {
//                SortInfo sInfo = mInfos.getSorts().get(i);
//                if (sInfo.isCheck()) {
//                    if (sort_ids.equals("")) {
//                        sort_ids = "" + sInfo.getId();
//                    } else {
//                        sort_ids += "," + sInfo.getId();
//                    }
//                }
//            }
            getDataBySource();
        }
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        initCarCount();
//    }

    private void initCarCount() {
        tvShopCart.setVisibility(View.GONE);
        new RetrofitRequest<CarCountInfo>(ApiRequest.getApiShiji().getCarCount()).handRequest(
                new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        if (msg.isSuccess()) {
                            isLogin = true;
                            tvShopCart.setVisibility(View.VISIBLE);
                            CarCountInfo info = (CarCountInfo) msg.obj;
                            tvShopCart.setText("" + info.getCount());
                            if (info.getCount() == 0) {
                                tvShopCart.setVisibility(View.GONE);
                            }

                        } else if (msg.isLossLogin()) {
                            tvShopCart.setVisibility(View.GONE);
                            isLogin = false;
                        }
                    }
                }
        );
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back:
                onBackPressed();
                break;
            case R.id.toolbar_right_layout:                                  // 跳转至购物车
                gotoShoppingCart();
                break;
            case R.id.tv_order:                                     // 显示排序浮层
                showOrderPopwindow();
                break;
            case R.id.tv_filter:                                    // 跳转至筛选界面
                Intent intentGoFilter = new Intent(GoodsListActivity.this, GoodsListFilterActivity.class);
//                intentGoFilter.putExtra("data", new Gson().toJson(mInfos, MallLimitOptionInfo.class));
                Util.saveDataToSp(mHandle,sharedPreferences,"goodsfilter",new Gson().toJson(mInfos));
                intentGoFilter.putExtra("fromGoods", true);
                intentGoFilter.putExtra("shopId", shopId);
                intentGoFilter.putExtra("source", source);
                intentGoFilter.putExtra("nFromIn", nFromIn);
                intentGoFilter.putExtra("word", word);
                if (source == 2) {
                    intentGoFilter.putExtra("categoryid", category_ids);
                }
                startActivityForResult(intentGoFilter, REQUEST_FILTER);
                overridePendingTransition(R.anim.slide_in_bottom_top, R.anim.slide_in_out_fixed);
                break;
        }
    }

//    private void goToCarView() {
//        HttpRequest.getInstance().isLogin(mHandle, new MsgCallBack() {
//            @Override
//            public void onResult(HttpMessage msg) {
//                if (msg.isSuccess()) {
//                    Intent intentGoShopCart = new Intent(GoodsListActivity.this, ShoppingCartActivity.class);
//                    intentGoShopCart.putExtra("reload", true);
//                    startActivity(intentGoShopCart);
//                } else if (msg.isLossLogin()) {
//                    Intent intent = new Intent(GoodsListActivity.this, LoginActivity.class);
//                    startActivity(intent);
//                    overridePendingTransition(R.anim.slide_in_top_buttom, R.anim.slide_out_top_buttom);
//                } else {
//                    showTips(msg.message);
//                }
//            }
//        });
//    }

    private void gotoShoppingCart() {
        if (isEffectClick()) {
            Intent intentGoShopCart = new Intent(GoodsListActivity.this, ShoppingCartActivity.class);
            startActivity(intentGoShopCart);
//            if (isLogin) {
//
//            } else {
//                Intent intent = new Intent(GoodsListActivity.this, LoginActivity.class);
//                startActivityForResult(intent, REQUEST_LOGIN);
//                overridePendingTransition(R.anim.slide_in_top_buttom, R.anim.slide_out_top_buttom);
//            }
        }
    }

    private void gotoGoodsDetail(final NewGoodsItem info) {
        if (isEffectClick()) {
            GoodsIdInfo goodsIdInfo = new GoodsIdInfo();
            goodsIdInfo.setGoodsId(info.getId());
            Intent intent = new Intent(GoodsListActivity.this, GoodsDetailActivity.class);
            intent.putExtra("data", new Gson().toJson(goodsIdInfo));
            startActivity(intent);
//            if (isLogin) {
//                GoodsIdInfo goodsIdInfo = new GoodsIdInfo();
//                goodsIdInfo.setGoodsId(info.getId());
//                Intent intent = new Intent(GoodsListActivity.this, GoodsDetailActivity.class);
//                intent.putExtra("data", new Gson().toJson(goodsIdInfo));
//                startActivity(intent);
//            } else {
//                Intent intent = new Intent(GoodsListActivity.this, LoginActivity.class);
//                startActivityForResult(intent, REQUEST_LOGIN);
//                overridePendingTransition(R.anim.slide_in_top_buttom, R.anim.slide_out_top_buttom);
//            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        DebugUtil.e("onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_FILTER) {
                String infoData = sharedPreferences.getString("goodsfilterdata","");
                //String infoData = data.getStringExtra("infoData");
                if(!TextUtils.isEmpty(infoData)) {
                    getCommitData(new Gson().fromJson(infoData, MallLimitOptionInfo.class));
                }
            } else if (requestCode == REQUEST_LOGIN) {
                initCarCount();
            }
        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initCarCount();
    }

    // 初始化购物车数量
//    private void initCarCiniount() {
//        tvCarcount.setVisibility(View.GONE);
//        HttpRequest.getInstance().getCarCount(mHandle, new MsgCallBack() {
//            @Override
//            public void onResult(HttpMessage msg) {
//                if (msg.isSuccess()) {
//                    isLogin = true;
//                    tvCarcount.setVisibility(View.VISIBLE);
//                    CarCountInfo info = (CarCountInfo) msg.obj;
//                    tvCarcount.setText("" + info.getCount());
//                    if (info.getCount() == 0) {
//                        tvCarcount.setVisibility(View.GONE);
//                    }
//
//                } else if (msg.isLossLogin()) {
//                    isLogin = false;
//                    tvCarcount.setVisibility(View.GONE);
//                }
//            }
//        });
//    }
}
